package com.center.growcenterserver.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.center.growcenterserver.common.R;
import com.center.growcenterserver.model.domain.Event;
import com.center.growcenterserver.model.request.EventRequest;
import com.center.growcenterserver.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/events")
public class EventController {

    @Autowired
    private EventService eventService;

    /**
     * 分页查询所有事件
     */
    @GetMapping("")
    public R getAllEvents(@RequestParam(defaultValue = "1") int curPage, @RequestParam(defaultValue = "10") int pageSize) {
        IPage<Event> page = new Page<>(curPage, pageSize);
        return eventService.getAllEvents(page);
    }

    /**
     * 根据 ID 查询单个事件
     */
    @GetMapping("/{id}")
    public R getEventById(@PathVariable String id) {
        return eventService.getEventById(id);
    }

    /**
     * 添加新事件
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addEvent(@RequestBody EventRequest eventRequest) {
        Map<String, Object> response = new HashMap<>();
        try {
            int result = eventService.addEvent(eventRequest);
            if (result == 1) {
                response.put("success", true);
                response.put("message", "Event added successfully");
            } else {
                response.put("success", false);
                response.put("message", "Failed to add event");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Error occurred: " + e.getMessage());
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * 更新事件信息
     */
    @PostMapping("/update")
    public R updateEvent(@RequestBody EventRequest eventRequest) {
        try {
            return eventService.updateEvent(eventRequest);
        } catch (Exception e) {
            return R.error("Failed to update the event");
        }
    }

    /**
     * 删除事件（支持单个或批量删除）
     */
    @GetMapping("/delete")
    public R deleteEvents(Long id, Long[] ids) {
        if (id != null) {
            // 单个删除
            return eventService.deleteEventById(id);
        } else if (ids != null && ids.length > 0) {
            // 批量删除
            return eventService.deleteEventsByIds(ids);
        } else {
            return R.error("Invalid request parameters for deletion");
        }
    }
}